package com.yyb.utils.neteaseim.api.impl;

import com.jiuqian.xdpx.aid.neteaseim.api.NeImBaseService;
import com.jiuqian.xdpx.aid.neteaseim.config.NeImProperties;
import com.jiuqian.xdpx.aid.neteaseim.util.CheckSumBuilder;
import com.yyb.utils.neteaseim.api.NeImBaseService;
import com.yyb.utils.neteaseim.config.NeImProperties;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author : Marshal
 * @Create : 2018/3/28 9:18
 * @Description : DOO
 */
@Service
@EnableConfigurationProperties(NeImProperties.class)
public class NeImBaseServiceImpl implements NeImBaseService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private NeImProperties imProperties;

    public NeImBaseServiceImpl(){}

    public NeImBaseServiceImpl(RestTemplate restTemplate, NeImProperties imProperties) {
        super();
        this.restTemplate = restTemplate;
        this.imProperties = imProperties;
    }


    @Override
    public <T> T build(MultiValueMap<String, String> params, String url, Class<T> responseType) {
        /*
                nonce和curTime不能定义为常量（即不能再inteface中定义），否则调用网易云接口是会报错
         */
        /** 随机数（最大长度128个字符） */
        String nonce = String.valueOf((int) ((Math.random() * 9 + 1) * 10000000));
        /** 当前UTC时间戳 */
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        /** 校验数 */
        String checkSum = CheckSumBuilder.getCheckSum(imProperties.getAppSecret(), nonce, curTime);

        HttpHeaders headers = new HttpHeaders();
        headers.add("AppKey", imProperties.getAppKey());
        headers.add("Nonce", nonce);
        headers.add("CurTime", curTime);
        headers.add("CheckSum", checkSum);
        headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");


        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);

        T postForObject = restTemplate.postForObject(url, requestEntity, responseType);
//        异常 ： java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        return  postForObject;
    }

}
